<template>
  <div class="user-center">
    <!-- 顶部用户信息卡片 -->
    <div class="user-card">
      <div class="user-info">
        <el-avatar :size="80" :src="userInfo.avatar" />
        <div class="user-details">
          <h2>{{ userInfo.nickname }}</h2>
          <p class="bio">{{ userInfo.bio }}</p>
          <div class="user-stats">
            <!-- <div class="stat-item">
              <span class="number">128</span>
              <span class="label">关注</span>
            </div>
            <div class="stat-item">
              <span class="number">256</span>
              <span class="label">粉丝</span>
            </div>
            <div class="stat-item">
              <span class="number">512</span>
              <span class="label">获赞</span>
            </div> -->
          </div>
        </div>
      </div>
      <el-button type="primary" plain @click="showEditDialog">编辑资料</el-button>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <i class="el-icon-s-order"></i>
              <div class="stat-info">
                <h3>我的订单</h3>
                <p>12个待处理</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <i class="el-icon-star-on"></i>
              <div class="stat-info">
                <h3>我的收藏</h3>
                <p>36个收藏</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <i class="el-icon-wallet"></i>
              <div class="stat-info">
                <h3>我的钱包</h3>
                <p>¥1288.00</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <i class="el-icon-tickets"></i>
              <div class="stat-info">
                <h3>优惠券</h3>
                <p>5张可用</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能导航区 -->
    <div class="function-nav">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="6" v-for="(item, index) in navItems" :key="index">
            <div class="nav-item" @click="handleNavClick(item)">
              <i :class="item.icon"></i>
              <span>{{ item.title }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 获取定位对话框 -->
    <el-dialog
      title="获取当前位置"
      :visible.sync="locationDialogVisible"
      width="30%"
      center>
      <div class="location-content">
        <p v-if="locationLoading">正在获取位置信息...</p>
        <div v-else-if="currentLocation">
          <p>当前位置：{{ currentLocation.address }}</p>
          <p>经纬度：{{ currentLocation.longitude }}, {{ currentLocation.latitude }}</p>
        </div>
        <p v-else class="error-message">{{ locationError }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="locationDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getCurrentLocation">重新获取</el-button>
      </span>
    </el-dialog>

    <!-- 最近活动 -->
    <div class="recent-activities">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>最近活动</span>
            <el-button type="text" @click="showAllActivities">查看全部</el-button>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.timestamp"
            :type="activity.type"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      title="编辑资料"
      :visible.sync="editDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            type="textarea"
            v-model="editForm.bio"
            :rows="3"
            placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 帮助中心对话框 -->
    <el-dialog
      title="帮助中心"
      :visible.sync="helpDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <help-center />
    </el-dialog>

    <!-- 账户安全对话框 -->
    <el-dialog
      title="账户安全"
      :visible.sync="accountSecurityVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <account-security @cancel="accountSecurityVisible = false" />
    </el-dialog>

    <!-- 消息中心对话框 -->
    <el-dialog
      title="消息中心"
      :visible.sync="messageCenterVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <message-center />
    </el-dialog>

    <!-- 所有活动对话框 -->
    <el-dialog
      title="所有活动"
      :visible.sync="allActivitiesVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in allActivities"
          :key="index"
          :timestamp="activity.timestamp"
          :type="activity.type"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
// 引入vue 和mapMutation 库
import { mapState, mapMutations } from "vuex";
import HelpCenter from './HelpCenter.vue';
import AccountSecurity from './AccountSecurity.vue';
import MessageCenter from './MessageCenter.vue';

export default {
  components:{
    ...mapState("loginModule", ["userinfo"]),
    HelpCenter,
    AccountSecurity,
    MessageCenter
  },
  name: 'UserCenter',
  data() {
    return {
      userInfo: {
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        nickname: 'admin',
        bio: '这个人很懒，什么都没留下~'
      },
      editDialogVisible: false,
      locationDialogVisible: false,
      helpDialogVisible: false,
      accountSecurityVisible: false,
      messageCenterVisible: false,
      locationLoading: false,
      currentLocation: null,
      locationError: '',
      amapKey: 'YOUR_AMAP_KEY', // 请替换为实际的高德地图API密钥
      editForm: {
        avatar: '',
        nickname: '',
        bio: ''
      },
      navItems: [
        { title: '我的订单', icon: 'el-icon-s-order' },
        { title: '我的收藏', icon: 'el-icon-star-on' },
        { title: '我的地址', icon: 'el-icon-location' },
        { title: '账号安全', icon: 'el-icon-lock' },
        { title: '消息中心', icon: 'el-icon-message' },
        { title: '帮助中心', icon: 'el-icon-question' },
        { title: '设置', icon: 'el-icon-setting' },
        { title: '退出登录', icon: 'el-icon-switch-button' }
      ],
      activities: [
        {
          content: '购买了商品：iPhone 13 Pro',
          timestamp: '2024-03-20 14:30',
          type: 'primary'
        },
        {
          content: '收藏了商品：MacBook Pro',
          timestamp: '2024-03-19 10:20',
          type: 'success'
        },
        {
          content: '修改了个人资料',
          timestamp: '2024-03-18 16:45',
          type: 'warning'
        }
      ],
      allActivitiesVisible: false,
      allActivities: [
        {
          content: '购买了商品：iPhone 13 Pro',
          timestamp: '2024-03-20 14:30',
          type: 'primary'
        },
        {
          content: '收藏了商品：MacBook Pro',
          timestamp: '2024-03-19 10:20',
          type: 'success'
        },
        {
          content: '修改了个人资料',
          timestamp: '2024-03-18 16:45',
          type: 'warning'
        },
        {
          content: '登录了系统',
          timestamp: '2024-03-17 09:15',
          type: 'info'
        },
        {
          content: '更新了收货地址',
          timestamp: '2024-03-16 11:30',
          type: 'primary'
        },
        {
          content: '使用了优惠券',
          timestamp: '2024-03-15 14:20',
          type: 'success'
        }
      ]
    }
  },
  methods: {
    ...mapMutations("loginModule", ["clearUser"]),
    showEditDialog() {
      this.editForm = {
        avatar: this.userInfo.avatar,
        nickname: this.userInfo.nickname,
        bio: this.userInfo.bio
      }
      this.editDialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      this.editForm.avatar = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    saveEdit() {
      // 这里应该调用API保存修改
      this.userInfo = { ...this.editForm }
      this.editDialogVisible = false
      this.$message.success('保存成功')
    },
    handleNavClick(item) {
      if (item.title === '我的地址') {
        this.locationDialogVisible = true;
        this.getCurrentLocation();
      } else if (item.title === '退出登录') {
        this.logout();
      } else if (item.title === '帮助中心') {
        this.helpDialogVisible = true;
      } else if (item.title === '账号安全') {
        this.accountSecurityVisible = true;
      } else if (item.title === '消息中心') {
        this.messageCenterVisible = true;
      } else {
        console.log('点击了：', item.title);
      }
    },
    logout() {
      // 清空vuex数据
      this.clearUser();
      // 清空本地存储
      localStorage.removeItem("user");
      // 跳转到登录页
      this.$router.push("/login");
    },
    getCurrentLocation() {
      this.locationLoading = true;
      this.locationError = '';
      this.currentLocation = null;

      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            // 使用高德地图API进行逆地理编码
            this.getAddressFromCoordinates(latitude, longitude);
          },
          (error) => {
            this.locationLoading = false;
            switch (error.code) {
              case error.PERMISSION_DENIED:
                this.locationError = '请允许浏览器获取位置权限';
                this.$message.error('请允许浏览器获取位置权限');
                break;
              case error.POSITION_UNAVAILABLE:
                this.locationError = '位置信息不可用，请检查GPS是否开启';
                this.$message.error('位置信息不可用，请检查GPS是否开启');
                break;
              case error.TIMEOUT:
                this.locationError = '获取位置超时，请重试';
                this.$message.error('获取位置超时，请重试');
                break;
              default:
                this.locationError = '获取位置时发生未知错误';
                this.$message.error('获取位置时发生未知错误');
            }
          },
          {
            enableHighAccuracy: true, // 使用高精度定位
            timeout: 5000, // 超时时间5秒
            maximumAge: 0 // 不使用缓存位置
          }
        );
      } else {
        this.locationLoading = false;
        this.locationError = '您的浏览器不支持地理位置功能';
        this.$message.error('您的浏览器不支持地理位置功能');
      }
    },
    getAddressFromCoordinates(latitude, longitude) {
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=${this.amapKey}&location=${longitude},${latitude}`;
      
      fetch(url)
        .then(response => response.json())
        .then(data => {
          this.locationLoading = false;
          if (data.status === '1') {
            this.currentLocation = {
              address: data.regeocode.formatted_address,
              longitude: longitude,
              latitude: latitude
            };
            this.$message.success('位置获取成功');
          } else {
            this.locationError = '获取地址信息失败';
            this.$message.error('获取地址信息失败');
          }
        })
        .catch(error => {
          this.locationLoading = false;
          this.locationError = '获取地址信息时发生错误';
          this.$message.error('获取地址信息时发生错误');
          console.error('Error:', error);
        });
    },
    showAllActivities() {
      this.allActivitiesVisible = true;
    }
  }
}
</script>

<style scoped>
.user-center {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.user-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.bio {
  color: #666;
  margin-bottom: 15px;
}

.user-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
}

.stat-item .number {
  font-size: 18px;
  font-weight: bold;
  display: block;
}

.stat-item .label {
  color: #666;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-content i {
  font-size: 36px;
  color: #409EFF;
}

.stat-info h3 {
  margin: 0;
  font-size: 16px;
}

.stat-info p {
  margin: 5px 0 0;
  color: #666;
}

.function-nav {
  margin-bottom: 20px;
}

.nav-item {
  text-align: center;
  padding: 20px 0;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item:hover {
  background-color: #f5f7fa;
  transform: translateY(-2px);
}

.nav-item i {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 10px;
  display: block;
}

.nav-item span {
  color: #333;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-activities {
  margin-bottom: 20px;
}

.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.location-content {
  text-align: center;
  padding: 20px;
  
  p {
    margin: 10px 0;
  }
  
  .error-message {
    color: #F56C6C;
  }
}
</style>